<?php
declare(strict_types=1);

namespace App\Controller\Backend;

use App\Logic\AdminEmailLogic;
use Exception;
use Hyperf\HttpServer\Annotation\AutoController;
use Psr\Http\Message\ResponseInterface;

#[AutoController(prefix: '/email', server: 'backend')]
class EmailController extends AbstractController
{
    /**
     * 模板列表
     * @return ResponseInterface
     */
    public function template(): ResponseInterface
    {
        return $this->apiReturn(200, 'succ', AdminEmailLogic::listTemplate());
    }

    /**
     * 修改模板
     * @return ResponseInterface
     */
    public function editTemplate(): ResponseInterface
    {
        $id = (int)$this->request->input('id', 0);
        if (!$id) {
            return $this->apiReturn(400, '参数错误');
        }
        $input = $this->request->all();
        if (isset($input['title']) && empty($input['title']) || empty($input['content'])) {
            return $this->apiReturn(400, '请将表单填写完整');
        }
        if (preg_match('/\{.*?}/', $input['content'])) {
            if(!json_validate($input['params'])) {
                return $this->apiReturn(400, '模板参数非json格式字符串');
            }
        } else {
            $input['params'] = '{}';
        }
        try {
            AdminEmailLogic::editTemplate($id, $input);
            return $this->apiReturn(200, '修改成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 发送日志
     * @return ResponseInterface
     */
    public function sendLog(): ResponseInterface
    {
        $input = $this->request->all();
        return $this->apiReturn(200, 'succ', AdminEmailLogic::sendLog($input));
    }
}